<template>
    <div class="edit-role-container">
        <el-card class="role-card">
            <template #header>
                <div class="card-header">
                    <el-icon class="header-icon">
                        <Avatar />
                    </el-icon>
                    <span class="card-title">编辑角色</span>
                </div>
            </template>

            <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="120px" class="role-form">
                <el-form-item label="角色名称：" prop="roleName">
                    <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
                </el-form-item>

              

                <el-form-item label="权限分配：" prop="permissions">
                    <el-form-item label="权限分配：" prop="permissonIds">
                    <el-checkbox-group v-model="roleForm.permissonIds">
                        <el-checkbox v-for="item in RoleData" :value="item.permissonId" :label="item.permissonName"
                            name="permissonIds">
                            {{ item.permissonName }}
                        </el-checkbox>

                    </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="update">修改</el-button>
                 
                </el-form-item>
                </el-form-item>

              
            </el-form>
        </el-card>
    


    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { Check, ArrowLeft, Avatar } from '@element-plus/icons-vue'
import axios from 'axios'
import { write } from '@/Until/axiosHepler'

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const router = useRouter()
const route = useRoute()
const roleFormRef = ref<FormInstance>()
    onMounted(() => {
    roleList();
})
const RoleData = ref<any[]>([])
const roleList = () => {
    axios.get("http://localhost:5134/api/User/PermissonList").then((res) => {
        RoleData.value = res.data.data;

    })
}

// 权限选项数据
const permissionOptions = [
    { value: '试题管理', label: '试题管理' },
    { value: '考试', label: '考试' },
    { value: '查看成绩', label: '查看成绩' },
    { value: '成绩分析', label: '成绩分析' },
    { value: '用户管理', label: '用户管理' },
    { value: '角色管理', label: '角色管理' },
    { value: '权限管理', label: '权限管理' },
    { value: '系统设置', label: '系统设置' }
]

// 角色表单数据类型定义
interface RoleForm {
    "roleId": number,
    "roleName": string,
    permissonIds:[],
}

// 初始化表单数据
const roleForm = reactive<RoleForm>({
    "roleId": 0,
    "roleName": "",
    "permissonIds": [],
   
})

// 表单验证规则
const rules = reactive<FormRules<RoleForm>>({
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
      
    ],
   
})

// 获取角色详情
const update =(row: any) => {

    axios.post("http://localhost:5219/api/Manger/UpdateRole",row).then((res=>{
       if(res.data.code==200)
       {
          roleForm.roleId=row.roleId
          roleForm.roleName=row.roleName
          roleForm.permissonIds=row.permissonIds||[]
          //这种方法直接反填
          ElMessage.success('修改成功');
     
       }
       else
       {
         ElMessage.success('修改失败');
       }
    }))
    // try {
    //     const response = await axios.get(`http://localhost:5219/api/Manger/UpdateRole/${roleId}`)

    //     if (response.data.code === 200 && response.data.data) {
    //         const data = response.data.data
    //         roleForm.roleId = data.roleId
    //         roleForm.roleName = data.roleName || ''
    //         roleForm.permissonIds=response.data.data
           
    //         ElMessage.success('角色详情加载成功')
    //     } else {
    //         ElMessage.error('获取角色详情失败')
    //     }
    // } catch (error) {
    //     console.error('获取角色详情出错:', error)
    //     ElMessage.error('获取角色详情失败')
    // }
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            updateRole().then(() => {
                axios.put(`http://localhost:5134/api/Role/UpdateRole/${roleForm.roleId}`, roleForm).then((res) => {
                    if (res.data.code === 200) {
                        ElMessage.success('角色更新成功！')
                        handleBack()
                    } else {
                        ElMessage.error('角色更新失败：' + res.data.message)
                    }
                })
            }).catch(error => {
                ElMessage.error('角色更新失败：' + error.message)
            })
        } else {
            console.log('表单验证失败', fields)
            ElMessage.error('请检查表单填写')
        }
    })
}

// 更新角色的API调用
const updateRole = async () => {
    try {
        const response = await axios.put(`http://localhost:5134/api/Role/UpdateRole/${roleForm.roleId}`, roleForm)

        if (response.data.code === 200) {
            return response.data
        } else {
            throw new Error(response.data.message || '更新角色失败')
        }
    } catch (error) {
        console.error('更新角色出错:', error)
        throw error
    }
}

// 返回上一页
const handleBack = () => {
    router.back()
}

// 组件挂载时获取数据
// onMounted(() => {
//     const roleId = route.query.roleId ? parseInt(route.query.roleId as string) : null
//     if (roleId) {
//         update(roleId)
//     } else {
//         ElMessage.warning('缺少角色ID参数')
//     }
// })
</script>

<style scoped>
.edit-role-container {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    padding: 40px 20px;
    background: #f5f7fa;
    min-height: calc(100vh - 64px);
}

.role-card {
    width: 100%;
    max-width: 800px;
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    border: 1px solid #e0e0e0;
    background: white;
    position: relative;
    overflow: hidden;
}

.role-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(90deg, #409eff, #67c23a);
    z-index: 1;
}

.card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 0;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
}

.header-icon {
    font-size: 22px;
    color: #409eff;
}

.card-title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
}

.role-form {
    width: 100%;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 40px;
}

.permission-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
    width: 100%;
}

.permission-checkbox {
    margin: 0;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-textarea__inner) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
    box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-textarea__inner:focus) {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-button) {
    min-width: 100px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

:deep(.el-button:hover) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
}

:deep(.el-checkbox) {
    margin-right: 0;
}

:deep(.el-checkbox__label) {
    font-weight: 500;
    color: #606266;
}

:deep(.el-switch) {
    --el-switch-on-color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .edit-role-container {
        padding: 20px 10px;
    }

    .role-card {
        max-width: 100%;
    }

    .form-actions {
        flex-direction: column;
        align-items: center;
    }

    :deep(.el-button) {
        width: 100%;
        max-width: 200px;
    }

    .permission-group {
        grid-template-columns: 1fr;
    }
}
</style>
